/*
 * PROJECT NAME: platform-shared
 * PACKAGE NAME: com.twsz.platform.util
 * FILE    NAME: BytesHelper.java
 * COPYRIGHT: Copyright(c) 2016 上海共进医疗科技有限公司 All Rights Reserved.
 */
package com.ontheroad.utils;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public final class BytesHelper {

	private BytesHelper() {}

	public static int toInt( byte[] bytes ) {
		int result = 0;
		for (int i=0; i<4; i++) {
			result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
		}
		return result;
	}
	
	/**
	 * 将十六进制组成的字符串转换为对半byte数值
	 * 
	 * @author qing.wang
	 * @date 2015年3月20日 下午4:43:00
	 * @param hexString
	 * @return
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			int cb = charToByte(hexChars[pos]) << 4;
			int cb2 = charToByte(hexChars[pos + 1]);
			d[i] = (byte) (cb | cb2);
		}
		return d;
	}

	/**
	 * 将十六进制字符输出对应十进制数值
	 * 
	 * @author qing.wang
	 * @date 2015年3月20日 下午4:43:05
	 * @param c
	 * @return
	 */
	public static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	/**
	 * @author qing.wang
	 * @date 2015年7月15日 下午4:12:05
	 * @param b
	 */
	@SuppressWarnings("unused")
	private static void writerToBin(byte[] b, String name) {
		String filename = "C:/Users/wxf/Desktop/bin/" + name + ".bin";
		try {
			DataOutputStream out = new DataOutputStream(new FileOutputStream(
					filename));
			out.write(b);
			out.close();
		} catch (IOException io) {
			System.out.println("problem writing " + filename);
		}
	}

	
}
